package com.blog.check.check;

import com.blog.check.resultenum.BlogChkRsEnum;
import com.blog.check.resultenum.CommentChkRsEnum;
import com.blog.dao.domain.BlogDO;
import com.blog.dao.domain.CommentDO;
import com.blog.form.CommentForm;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class CommentCheck extends BaseCheck {

    /**
     * 检查保存
     *
     * @param commentForm 评论形式
     * @return {@link CheckResult}
     */
    public CheckResult checkSave(CommentForm commentForm){
        // Non-logical check for save
        CheckResult checkResult = checkSaveNonLogic(commentForm);
        if (checkResult.getCode() != CheckResult.success().getCode()){
            return checkResult;
        }
        // logical check for save
        checkResult = checkSaveLogic(commentForm);
        return  checkResult;
    }

    private CheckResult checkSaveLogic(CommentForm commentForm) {

        if (getUsername() == null){
            return CheckResult.failure(CommentChkRsEnum.USERNAME_IS_NOT_LOGIN);
        }
        BlogDO blogDO = blogDAO.get(commentForm.getBlogId());
        if (ObjectUtils.isEmpty(blogDO)){
            return CheckResult.failure(CommentChkRsEnum.ILLEGAL_BLOG_ID_NOT_EXIST,commentForm.getBlogId());
        }
        return CheckResult.success();
    }

    private CheckResult checkSaveNonLogic(CommentForm commentForm) {

        if (StringUtils.isBlank(commentForm.getContent())){
            return CheckResult.failure(CommentChkRsEnum.CONTENT_MUST_NOT_BE_NULL);
        }
        return CheckResult.success();
    }


    /**
     * 检查删除
     *
     * @param commentId 评论id
     * @return {@link CheckResult}
     */
    public CheckResult checkRemove(String commentId){
        // Non-logical check for update
        CheckResult checkResult =  checkRemoveNonLogic(commentId);
        if (checkResult.getCode() != CheckResult.success().getCode()){
            return checkResult;
        }
        // logical check for save
        checkResult = login(commentId);

        return checkResult;
    }

    private CheckResult login(String commentId) {

        CommentDO commentDO = commentDAO.get(commentId);
        BlogDO blogDO = blogDAO.get(commentDO.getBlogId());
        String username = commentDO.getUsername();
        String blogUser = blogDO.getKeyWord();

        if (!Objects.equals(getUsername(), username) || !Objects.equals(getUsername(), blogUser)){
            return CheckResult.failure(BlogChkRsEnum.USER_IS_NOT_LOGIN);
        }
        return CheckResult.success();
    }

    private CheckResult checkRemoveNonLogic(String commentId) {
        CommentDO commentDO = commentDAO.get(commentId);
        if (ObjectUtils.isEmpty(commentDO)){
            return CheckResult.failure(CommentChkRsEnum.ILLEGAL_ID_NOT_EXIST,commentId);
        }
        return CheckResult.success();
    }
}
